import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:openchina/common/event_bus.dart';
import 'package:openchina/constants/constants.dart'
    show AppColors, AppInfo, AppUrls;
import 'package:openchina/pages/login_web_page.dart';
import 'package:openchina/pages/my_message_page.dart';
import 'package:openchina/pages/profile_detail_page.dart';
import 'package:openchina/pages/test_refresh_page.dart';
import 'package:openchina/utils/data_util.dart';
import 'package:openchina/utils/net_util.dart';

class ProfilePage extends StatefulWidget {
  @override
  _ProfilePageState createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  List menuTitles = ['我的消息', '阅读记录', '我的博客', '我的问答', '我的活动', '我的团队', '邀请好友'];
  List menuIcons = [
    Icons.message,
    Icons.chrome_reader_mode,
    Icons.book,
    Icons.question_answer,
    Icons.local_activity,
    Icons.people,
    Icons.layers
  ];
  String userAvatar;
  String userName;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //尝试显示用户信息
    _showUserInfo();
    //eventbus监听登录事件
    eventBus.on<LoginEvent>().listen((event) {
      //TODO 获取用户信息并展示
      _getUserInfo();
    });
    //event监听登出事件
    eventBus.on<LogoutEvent>().listen((event) {
      //TODO 退出处理用户信息
      _showUserInfo();
    });
  }

  _getUserInfo() {
    DataUtil.getTokenAccess().then((accessToken) {
      if (accessToken.length <= 0) {
        return;
      }
      Map<String, dynamic> params = Map<String, dynamic>();
      params['access_token'] = accessToken;
      params['dataType'] = AppInfo.JSON;
      NetUtil.get(AppUrls.OPENAPI_USER, params).then((data) {
//        {"gender":"male","name":"有点凉了","location":"北京 海淀","id":1991319,"avatar":"https://www.oschina.net/img/portrait.gif","email":"120476536@qq.com","url":"https://my.oschina.net/u/1991319"}
        print('登录个人信息 $data');
        if (data != null) {
          Map<String, dynamic> map = json.decode(data);
          if (mounted) {
            setState(() {
              userAvatar = map['avatar'];
              userName = map['name'];
            });
          }
          DataUtil.savaUserInfo(map);
        }
      });
    });
  }

  _showUserInfo() {
    DataUtil.getUserInfo().then((user) {
      if (mounted) {
        setState(() {
          if (user != null) {
            userAvatar = user.avatar;
            userName = user.name;
          } else {
            userAvatar = null;
            userName = null;
          }
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return ListView.separated(
        itemBuilder: (context, index) {
          if (index == 0) {
            return _buildHeader();
          }
          index -= 1;
          return ListTile(
            leading: Icon(menuIcons[index]),
            title: Text(menuTitles[index]),
            trailing: Icon(Icons.arrow_forward_ios),
            onTap: () {
              //TODO
              DataUtil.isLogin().then((isLogin) {
                if (isLogin) { 
                  switch (index) {
                    case 0:
                      Navigator.of(context).push(MaterialPageRoute(builder: (context) => MyMessagePage()));
                      break;
                    case 1:
                      Navigator.of(context).push(MaterialPageRoute(builder: (context) => TestRefreshPage()));
                      break;
                  }
                } else {
                  _login();
                }
              });
            },
          );
        },
        separatorBuilder: (context, index) {
          return Divider(
            height: 1.0,
          );
        },
        itemCount: menuTitles.length + 1);
  }

  _login() async {
    final result = await Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => LoginWebPage(),
      ),
    );
    if (result != null && result == 'refresh') {
      //跳转过去后下一个界面约定子弹表示登录成功
      eventBus.fire(LoginEvent()); //登录成功通知loginEvent
    }
  }

  Container _buildHeader() {
    return Container(
      color: Color(AppColors.APP_THEME),
      height: 200.0,
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            //头像
            GestureDetector(
              onTap: () {
                DataUtil.isLogin().then((isLogin) {
                  if (isLogin) {
                    //TODO 详情
                    Navigator.of(context).push(MaterialPageRoute(
                        builder: (context) => ProFileDetailPage()));
                  } else {
                    //TODO 登录
                    _login();
                  }
                });
              },
              child: userAvatar != null
                  ? Container(
                      height: 60.0,
                      width: 60.0,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        border: Border.all(
                          width: 2.0,
                          color: Color(AppColors.CONTAINER_BACK),
                        ),
                        image: DecorationImage(
                            image: NetworkImage(userAvatar), fit: BoxFit.cover),
                      ),
                    )
                  : Container(
                      height: 60.0,
                      width: 60.0,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        border: Border.all(
                          width: 2.0,
                          color: Color(AppColors.CONTAINER_BACK),
                        ),
                        image: DecorationImage(
                            image: AssetImage(
                                'assets/images/ic_avatar_default.png'),
                            fit: BoxFit.cover),
                      ),
                    ),
            ),
            SizedBox(
              height: 10.0,
            ),
            userName != null
                ? Text(
                    userName,
                    style: TextStyle(
                      color: Color(AppColors.CONTAINER_BACK),
                    ),
                  )
                : Text(
                    '点击头像登录',
                    style: TextStyle(
                      color: Color(AppColors.CONTAINER_BACK),
                    ),
                  ),
            //用户名
          ],
        ),
      ),
    );
  }
}
